package com.ruoyi.web.controller.community.electronicCommerce;


import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.community.domain.*;
import com.ruoyi.community.mapper.*;
import com.ruoyi.community.service.ec.*;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/community/ec")
public class electronicCommerceAppController extends BaseController {


    @Autowired
    private IEcRestaurantsService ecRestaurantsService;

    @Autowired
    private IEcActivityService ecActivityService;

    @Autowired
    private IEcFoodsService ecFoodsService;

    @Autowired
    private IEcOrdersService ecOrdersService;

    @Autowired
    private IEcFoodsInOrderService ecFoodsInOrderService;

    @Autowired
    private HelpCommentMapper helpCommentMapper;

    @Autowired
    private EcCommentMapper ecCommentMapper;

    @Autowired
    private EcFoodsInOrderMapper ecFoodsInOrderMapper;

    @Autowired
    private EcRestaurantsMapper ecRestaurantsMapper;

    @Autowired
    private SysCommunityMapper sysCommunityMapper;

    @Autowired
    private EcAddressMapper ecAddressMapper;

    @Autowired
    private ISysUserService userService;




    /**
     * app端首页请求社区名称
     */
    @GetMapping("/community")
    public AjaxResult community()
    {
        Integer c = SecurityUtils.getCommunityId();
        String str = sysCommunityMapper.selectSysCommunityById(c).getName();
        System.out.println(str);
        return AjaxResult.success(str);
    }
    /**
     * app端首页请求店铺列表
     */
    @GetMapping("/list")
    public AjaxResult list()
    {
        Integer c = SecurityUtils.getCommunityId();

        List<EcRestaurants> list = ecRestaurantsService.selectEcRestaurantsListByCommunity(c);
        List<EcStoreApp> storeList= new ArrayList<EcStoreApp>();
        for(int i=0;i<list.size();i++){
            EcRestaurants r = list.get(i);
            EcStoreApp s = new EcStoreApp();
            s.setAveragePrice(r.getAveragePrice());
            s.setDelPrice(r.getDeliveryPrice());
            s.setSaleMonth(r.getMouthOrderNum());
            s.setScore(r.getRating());
            s.setStoreId(r.getRestaurantId());
            s.setStoreImgUrl(r.getImagePath());
            s.setStoreName(r.getName());
            List<EcActivity> a = ecActivityService.selectEcActivityByRestaurantId(r.getRestaurantId());
            s.setActives(a);
            storeList.add(s);
        }
        return AjaxResult.success(storeList);
    }

    /**
     * app端首页search店铺列表
     */
    @GetMapping("/listSearch")
    public AjaxResult listSearch(String name) {
        System.out.println(name);
        Integer c = SecurityUtils.getCommunityId();
        Map map = new HashMap();
        map.put("communityId",c);
        map.put("name",name);

        List<EcRestaurants> list = ecRestaurantsMapper.selectByCommunityIdAndName(map);

        List<EcStoreApp> storeList= new ArrayList<EcStoreApp>();
        for(int i=0;i<list.size();i++){
            EcRestaurants r = list.get(i);
            EcStoreApp s = new EcStoreApp();
            s.setAveragePrice(r.getAveragePrice());
            s.setDelPrice(r.getDeliveryPrice());
            s.setSaleMonth(r.getMouthOrderNum());
            s.setScore(r.getRating());
            s.setStoreId(r.getRestaurantId());
            s.setStoreImgUrl(r.getImagePath());
            s.setStoreName(r.getName());
            List<EcActivity> a = ecActivityService.selectEcActivityByRestaurantId(r.getRestaurantId());
            s.setActives(a);
            storeList.add(s);
        }
        return AjaxResult.success(storeList);
    }


    /**
     * app端店铺分类页
     */
    @GetMapping("/category")
    public AjaxResult category(Integer category) {
        Integer c = SecurityUtils.getCommunityId();
        Map map = new HashMap();
        map.put("communityId",c);
        map.put("categoryId",category);

        List<EcRestaurants> list = ecRestaurantsMapper.selectByCommunityIdAndCategory(map);

        List<EcStoreApp> storeList= new ArrayList<EcStoreApp>();
        for(int i=0;i<list.size();i++){
            EcRestaurants r = list.get(i);
            EcStoreApp s = new EcStoreApp();
            s.setAveragePrice(r.getAveragePrice());
            s.setDelPrice(r.getDeliveryPrice());
            s.setSaleMonth(r.getMouthOrderNum());
            s.setScore(r.getRating());
            s.setStoreId(r.getRestaurantId());
            s.setStoreImgUrl(r.getImagePath());
            s.setStoreName(r.getName());
            List<EcActivity> a = ecActivityService.selectEcActivityByRestaurantId(r.getRestaurantId());
            s.setActives(a);
            storeList.add(s);
        }
        return AjaxResult.success(storeList);
    }

    /**
     * app端店铺页请求食品列表
     */
    @GetMapping("/foodlist")
    public AjaxResult foodList(Long restaurantId)
    {

        List<EcFoods> ecFoodsList = ecFoodsService.selectEcFoodsListByRestaurantId(restaurantId);
        if(ecFoodsList!=null) {
            List<EcFoodsApp> list = new ArrayList<EcFoodsApp>();

            Map<String, List<EcFoods>> stringListMap = ecFoodsList.stream().collect(Collectors.groupingBy(EcFoods::getCategoryName));

            for (Map.Entry<String, List<EcFoods>> entry : stringListMap.entrySet()) {
                //System.out.println("key = " + entry.getKey() + ", value = " + entry.getValue());
                EcFoodsApp a = new EcFoodsApp();
                List<EcFoods> e = entry.getValue();
                a.setTitle(entry.getKey());
                a.setTitleId(e.get(0).getCategoryId());
                a.setFoodCount(0);
                a.setItems(e);
                list.add(a);
            }


            return AjaxResult.success(list);
        }
        return AjaxResult.error("空查询");
    }

    /**
     * app端店铺页请求店铺信息
     */
    @GetMapping("/storeinfo")
    public AjaxResult storeInfo(Long restaurantId)
    {

       EcRestaurants r = ecRestaurantsService.selectEcRestaurantsById(restaurantId);
       EcStoreApp s = new EcStoreApp();
       s.setAveragePrice(r.getAveragePrice());
       s.setDelPrice(r.getDeliveryPrice());
       s.setSaleMonth(r.getMouthOrderNum());
       s.setScore(r.getRating());
       s.setStoreId(r.getRestaurantId());
       s.setStoreImgUrl(r.getImagePath());
       s.setStoreName(r.getName());
       s.setPublicMsg(r.getDescription());
       List<EcActivity> a = ecActivityService.selectEcActivityByRestaurantId(r.getRestaurantId());
       s.setActives(a);
       return  AjaxResult.success(s);

    }
    /**
     * app端订单页请求订单信息
     */
    @GetMapping("/orderlist")
    public AjaxResult orderList()
    {
        Long userId = SecurityUtils.getUserID();
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<EcOrders> ordersList = ecOrdersService.selectEcOrdersListByUserId(userId);
        List<EcOrdersApp> o = new ArrayList<EcOrdersApp>();
        for(int i=0;i<ordersList.size();i++){
            EcOrders ecOrders = ordersList.get(i);
            EcOrdersApp ecOrdersApp = new EcOrdersApp();
            ecOrdersApp.setDate(sdf.format(ecOrders.getTime()));
            ecOrdersApp.setHowToDistribute(ecOrders.getDescription());
            ecOrdersApp.setId(ecOrders.getOrderId().longValue());
            ecOrdersApp.setPrice(ecOrders.getTotalPrice());
            EcRestaurants r = ecRestaurantsService.selectEcRestaurantsById(ecOrders.getRestaurantId());
            ecOrdersApp.setRestaurantName(r.getName());
            ecOrdersApp.setPic(r.getImagePath());
            switch(ecOrders.getStatus()){
                case 1:
                    ecOrdersApp.setState("已完成");
                    break;
                case 2:
                    ecOrdersApp.setState("配送中");
                    break;
                case 0:
                    ecOrdersApp.setState("已取消");
                    break;
                case 3:
                    ecOrdersApp.setState("已评论");
                    break;
            }
            o.add(ecOrdersApp);
        }

        return  AjaxResult.success(o);

    }


    /**
     * app端订单页请求订单信息
     */
    @GetMapping("/orderdetail")
    public AjaxResult orderDetail(@PathVariable Long orderId)
    {
        SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        EcOrders ecOrders = ecOrdersService.selectEcOrdersById(orderId);
        EcOrderDetailApp eoda = new EcOrderDetailApp();
        eoda.setAddress(ecOrders.getUserAddress());
        eoda.setDate(sdf.format(ecOrders.getTime()));
        eoda.setDeliverFee(ecOrders.getDeliveryPrice());
        eoda.setOrderId(ecOrders.getOrderId().longValue());
        eoda.setTotalPrice(ecOrders.getTotalPrice());
        eoda.setStoreId(ecOrders.getRestaurantId());
        EcRestaurants r = ecRestaurantsService.selectEcRestaurantsById(ecOrders.getRestaurantId());
        eoda.setStoreName(r.getName());
        switch(ecOrders.getStatus()){
            case 1:
                eoda.setState("已完成");
                break;
            case 2:
                eoda.setState("配送中");
                break;
            case 0:
                eoda.setState("已取消");
                break;
            case 3:
                eoda.setState("已评论");
                break;
        }

        switch(ecOrders.getPayMethod()){
            case 1:
                eoda.setBy("微信支付");
                break;
            case 2:
                eoda.setBy("余额支付");
                break;
        }
        List<EcFoodsInOrder> q = ecFoodsInOrderService.selectEcFoodsInOrderByOrderId(ecOrders.getOrderId().intValue());
        eoda.setCart(q);
        return  AjaxResult.success(eoda);


    }


    /**
     * 电商支付
     * @param ecPayApp
     * @return
     */
    @PostMapping("/pay")
    public AjaxResult pay(@RequestBody EcPayApp ecPayApp){
        EcOrders ecOrder = new EcOrders();
        ecOrder.setCommunityId(SecurityUtils.getCommunityId());
        ecOrder.setUserId(SecurityUtils.getUserID());
        ecOrder.setPayMethod(ecPayApp.getPayment());
        ecOrder.setDeliveryPrice(ecPayApp.getDelPrice());
        ecOrder.setDescription(ecPayApp.getDescription());
        ecOrder.setStatus(2);//设置为配送中
        ecOrder.setTime(new Date());
        ecOrder.setRestaurantId(ecPayApp.getStoreId());
        ecOrder.setTotalPrice(ecPayApp.getPrice());
        ecOrder.setUserAddress(ecPayApp.getAddress());
        //SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHHmmss");
        Date t = new Date();
        System.out.println(t.hashCode());
        //这里缺个随机数
        BigInteger b = new BigInteger(String.valueOf(t.getDate()*100+(int)ecPayApp.getPrice()+t.getHours()+t.hashCode()));

        ecOrder.setOrderId(b);
        System.out.println(ecOrder.getOrderId());

        ecOrdersService.insertEcOrders(ecOrder);

        for(int i=0;i<ecPayApp.getCart().size();i++)
        {
            EcFoodsInOrder e1 = new EcFoodsInOrder();
            EcFoods e2 = ecPayApp.getCart().get(i);
            e1.setNum(e2.getCount());
            e1.setFoodId(e2.getFoodsId());
            e1.setFoodName(e2.getName());
            e1.setOrderId(ecOrder.getOrderId().intValue());
            e1.setPrice(e2.getPrice());
            ecFoodsInOrderService.insertEcFoodsInOrder(e1);
        }


        //修改积分

//        if(integral>0) {
//            IntDetails details = new IntDetails();
//            details.setOperationId(1);
//            details.setContent("缴费抵扣");
//            details.setType(0);
//            details.setIntegral(integral);
//            intDetailsService.insertIntDetails(details);
//        }

        return toAjax(1);



    }




    /**
     * 提交评论
     * @param ecPayApp
     * @return
     */
    @PostMapping("/comment")
    public AjaxResult comment(@RequestBody HelpComment helpComment){

        Long orderId= helpComment.getGoodsId();
        EcOrders ecOrders = ecOrdersService.selectEcOrdersById(orderId);
        Long shopId = ecOrders.getRestaurantId();
        ecOrders.setStatus(3);
        ecOrdersService.updateEcOrders(ecOrders);
        List<EcFoodsInOrder> ecFoodsInOrderList = ecFoodsInOrderMapper.selectEcFoodsInOrderByOrderId(orderId.intValue());

        if(shopId==0) {

            for (int i = 0; i < ecFoodsInOrderList.size(); i++) {
                Long foodId = ecFoodsInOrderList.get(i).getFoodId();
                HelpComment helpComment1 = new HelpComment();
                helpComment1.setUserId(SecurityUtils.getUserID());
                helpComment1.setDate(new Date());
                helpComment1.setGoodsId(foodId);
                helpComment1.setContent(helpComment.getContent());
                helpComment1.setScore(helpComment.getScore());
                helpComment1.setContentPicture(helpComment.getContentPicture());
                helpCommentMapper.insert(helpComment1);

            }
        }else{
            for (int i = 0; i < ecFoodsInOrderList.size(); i++) {
                Long foodId = ecFoodsInOrderList.get(i).getFoodId();
                EcComment ecComment1 = new EcComment();
                ecComment1.setUserId(SecurityUtils.getUserID());
                ecComment1.setDate(new Date());
                ecComment1.setGoodsId(foodId);
                ecComment1.setContent(helpComment.getContent());
                ecComment1.setScore(helpComment.getScore());
                ecComment1.setContentPicture(helpComment.getContentPicture());
                ecCommentMapper.insert(ecComment1);
            }

        }


        return toAjax(1);


    }


    /**
     * 电商评价列表
     * @param
     * @return
     */
    @GetMapping("/comments")
    public AjaxResult goodComment(Long id)
    {
        List<EcComment> ecCommentList = ecCommentMapper.selectByRestaurantId(id);
        for(int i=0;i<ecCommentList.size();i++)
        {
            EcComment h = ecCommentList.get(i);
            Long userId = h.getUserId();
            SysUser u = userService.selectUserById(userId);
            h.setUserName(u.getUserName());
            h.setUserPicture(u.getAvatar());
        }
        return  AjaxResult.success(ecCommentList);

    }


    /**
     * 添加地址
     * @param
     * @return
     */
    @PostMapping("/addAddress")
    public AjaxResult addAddress(@RequestBody EcAddress ecAddress){
        ecAddress.setUserId(SecurityUtils.getUserID());
        ecAddress.setCommunityId(SecurityUtils.getCommunityId());

       return AjaxResult.success(ecAddressMapper.insertEcAddress(ecAddress));


    }



    /**
     * 获得地址列表
     */
    @GetMapping("/getAddressList")
    public AjaxResult getAddressList()
    {
        Long userId = SecurityUtils.getUserID();
        Map map = new HashMap();
        map.put("userId",userId);
        map.put("communityId",SecurityUtils.getCommunityId());

        return AjaxResult.success(ecAddressMapper.selectEcAddressListByUserIdAndCommunityId(map));
    }

    /**
     * 删除地址
     */
    @GetMapping("/deleteAddress")
    public AjaxResult deleteAddress(Integer id)
    {

        return AjaxResult.success(ecAddressMapper.deleteEcAddressById(id));
    }








}
